﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BySoft.Web.Utility;
using BySoft.Server.Common;
using BySoft.Server.Consts;
using BySoft.Server.Common.Entity;
using BySoft.Server.Business;
using BySoft.Server.Common.Enum;
using OneSoft.EntityCore;
using System.Web.UI.HtmlControls;
using ZCZP.Web.Site;
using System.Web;

namespace BySoft.Web.Site.OutSource
{
    public partial class KnifeInStockEdit : AuthBasePage
    {
        #region 属性定义
        private string m_strsequenceName = "BsKnifeinstock" + DateTime.Now.ToString("yyyyMMdd");
        private string m_strTbl = "BS_KnifeInStock";
        private string m_strMainKey = "BillID";

        private DataTable DtKnifeInStockData
        {
            get
            {
                if (null == Session["KnifeInStockData"])
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["KnifeInStockData"];
                }
            }
            set
            {
                Session["KnifeInStockData"] = value;
            }
        }

        private DataTable CreateDT()
        {
           
            return  BsKnifeinstock.CreateDetailDT();
        }
        #endregion

        #region 初始化及绑定控件
        private void InitData()
        {
            DtKnifeInStockData = null;
            
            SetControlAttr(new BsKnifeinstockEntity(), tBase);
            string strCode = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id").Trim());
            InitHead(strCode);
            InitBody(strCode);
        }
        private void InitHead(string strCode)
        {
            DataTable dt = BsKnifeinstock.SelectHeadData(strCode);
            DBtoControlHead(this.Page, dt, tBase, @"../OutOrder/OutMatReturnList.aspx");
            DataRow row = dt.Rows[0];
             hdCode.Value = CommonMethod.GetString(row["BillID"]);
             hidSupplierID.Value = CommonMethod.GetString(row["SupplierID"]);
             txtSupplierName.Text = CommonMethod.GetString(row["SupplierName"]);
        }

        private void InitBody(string strCode)
        {
            DataTable dt = BsKnifeinstock.SelectDetailData(strCode);
           
            DtKnifeInStockData = dt.Copy();
            BindData();
        }


        #endregion

        #region 控件事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grdResult.Style.Add("word-break", "keep-all");
                grdResult.Style.Add("word-wrap", "normal");
                InitData();
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }

       

        private void GetGridViewData()
        {
            DataTable dttemp = CreateDT();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                Label lblKnifeID = gvr.FindControl("lblKnifeID") as Label;
                if (lblKnifeID == null || string.IsNullOrEmpty(lblKnifeID.Text.Replace("&nbsp;", "")))
                {
                    continue;
                }

               
                 Label lblDetailID1 = gvr.FindControl("lblDetailID") as Label;
                TextBox txtNum1 = gvr.FindControl("txtNums") as TextBox;
                TextBox txtPrice1 = gvr.FindControl("txtPrice") as TextBox;
                TextBox txtAmount1 = gvr.FindControl("txtAmount") as TextBox;


                DataRow row = dttemp.NewRow();
                row["DetailID"] = GetGridViewString(lblDetailID1);
                row["KnifeID"] = GetGridViewString(lblKnifeID);
                decimal nums =(decimal) GetGridViewDecimal(txtNum1);

                decimal price = (decimal)GetGridViewDecimal(txtPrice1);


                row["Nums"] = nums;
                row["Price"] = price;
                row["Amount"] = price*nums;
               

                dttemp.Rows.Add(row);
            }
            dttemp.AcceptChanges();
            DtKnifeInStockData = dttemp;
        }

        private void BindData()
        {
            DataView dv = new DataView(DtKnifeInStockData);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["DetailID"] = index;
                   // dr["WorkOrderNo"] = txtOrderID.Text.Trim() + index.ToString();
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }

            UIHelper.RunScript(this.UpdatePanel2, "Refreashtab();");
        }


        //protected void btnAdd_Click(object sender, EventArgs e)
        //{
        //    GetGridViewData();
        //    UIHelper.RunScript(this.Page, "importNewRow();");
          
        //}

        protected void btnSelectSupplier_Click(object sender, EventArgs e)
        {
            txtSupplierName.Text = "";
            if (string.IsNullOrEmpty(hidSupplierID.Value))
            {
                return;
            }
            MdSupplierEntity en = MdSupplier.GetMdSupplierByID(hidSupplierID.Value);

            txtSupplierName.Text = en.SupplierName;
            UIHelper.RunScript(this.UpdatePanel2, "Refreashtab();");
        }
        protected void btnAddh_Click(object sender, EventArgs e)
        {
            BindData();
        }

       

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }

            BsKnifeinstockEntity entity = new BsKnifeinstockEntity();
            
            entity.SupplierID = GetString(hidSupplierID);

            entity.BillDate = GetDateTime(lblBillDate);
            entity.BillID = GetString(lblBillID);
            entity.Status = "1";
            entity.ModifyUserID = CurrentUser.UserID;
            entity.ModifyUserName = CurrentUser.UserName;
            entity.ModifyDate = DateTime.Now;
         
          



            BsKnifeinstock.SaveOrUpdate(entity, DtKnifeInStockData,false);
            base.LogAction(BaseEnum.ActionType.Add, entity.BillID, true, null, new EntityBase[] { entity });
            DtKnifeInStockData = null;
            UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../Knife/KnifeInStockList.aspx");
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string str = e.CommandArgument.ToString();
                int iDel = CommonMethod.ConvertToInt(str);
                GetGridViewData();
                DataTable dt = DtKnifeInStockData.Copy();
                dt.Rows.RemoveAt(iDel);
                DtKnifeInStockData = dt.Copy();
                BindData();
                UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + 
                        Message.ConfirmDelete +

                        "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion

              
            }
        }

      
        //     protected void btnSelectBillID_Click(object sender, EventArgs e)
        //{
        //    BindDetailData();

        //}

        //private void BindDetailData()
        //{
        //    string strBillID = hidBillID.Value.Trim();

        //    if (string.IsNullOrEmpty(strBillID))
        //    {
        //        return;
        //    }
        //    DataTable dtTemp = CreateDT();

        //    DataTable dt = BsKnifeinstock.SelectOutProcessDetail(lblBillID.Text, strBillID);
          
        //    if (dt.Rows.Count != 0)
        //    {

        //        DataRow dr = dt.Rows[0];
        //        txtWorkOrderNo.Text = CommonMethod.GetString(dr["WorkOrderNo"]);
        //        txtScheduleID.Text = CommonMethod.GetString(dr["ScheduleID"]);
        //        hidSupplierID.Value = CommonMethod.GetString(dr["SupplierID"]);
        //        txtSupplierName.Text = CommonMethod.GetString(dr["SupplierName"]);
        //        txtBillID.Text = strBillID;



        //        DtKnifeInStockData = CommonMethod.CopyDTtoDT(dt, dtTemp);

        //    }
        //    BindData();
        //}

        #endregion

        #region 本地方法
        private bool ValidateData()
        {
            string strMention = "";


            //if (ClsComm.CheckExist(m_strTbl, m_strMainKey, lblBillID.Text.Trim(), true))
            //    {
            //        strMention = "委外件退料编号已经存在！<br />";
            //    }

                GetGridViewData();

                DataTable dt = DtKnifeInStockData;
                decimal sum = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    sum +=CommonMethod.ConvertToDecimal(dr["Nums"],2);
                }
                if (sum<=0)
                {
                    strMention = "退回数量不可为空！<br />";
                }
               
            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }
        #endregion


    }
}

